(function(window) {
    // 把三个状态设为常量
    const PENDING = 'pending'
    const FULFILLED = 'fulfilled'
    const REJECTED = "rejected"
    function Promise(excutor) {
        // 设置构造函数的属性
        this.state = PENDING; //默认值
        this.data = undefined; //默认值
        // 保存待处理回调的数组: [{resolved () {}, rejected () {}}, {resolved () {}, rejected () {}}] => callbacks
        this.callbacks = []
        let self = this;
        function resolve (value) {
            // 原因：只有当前状态为pending， 才会去改变状态，继续向下处理 （只改变一次，处理 resolve(11),后面紧跟reject() 的状态，只执行第一个，后面的不执行）
            if (self.state !== PENDING) return ;
            self.state = FULFILLED;
            self.data = value;
            setTimeout(() => {
                self.callbacks.forEach(callbackObj => callbackObj.resolved(value))
            } , 0)
        }
        function reject(reason) {
            if (self.state !== PENDING) return ;
            self.state = REJECTED;
            self.data = reason;
            setTimeout(() => {
                self.callbacks.forEach(callbackObj => callbackObj.rejected(reason))
            } , 0)
        }
        // 当函数中，抛出一个错误时
        try {
            excutor(resolve, reject);//执行器函数是回调函数，
        } catch (error) {
            reject(error)
        }
        
    }
    Promise.prototype.then = function(Onresolved, Onrejected) { // Onresolved, Onrejected 函数的形参，在then方法的实参
        //resolve直接执行的时候，then中的Onresolved，开始异步读取resolve的结果，即 成功状态的promise，异步执行成功的回调
        const self = this;
        if(self.state === FULFILLED) {
            setTimeout(() => {
                Onresolved(self.data)
            }, 0);
        } else if (self.state === REJECTED) {
            setTimeout(() => {
                Onrejected(self.data);
            }, 0);
        }
        // 待处理的回调
        this.callbacks.push({
            resolved: Onresolved,
            rejected: Onrejected
        })

    }
    Promise.prototype.catch = function(Onresolved, Onrejected) {

    }
    Promise.resolve = function (value) {

    }
    Promise.reject = function (reason) {
        
    }
    Promise.all = function (promises) {

    }
    Promise.race = function (promises) {
        
    }
    Promise.allSettled = function (promises) {

    }
    
    window.Promise = Promise;
})(window)